﻿using _15Net8AspNetCore_ORM.Context;
using _15Net8AspNetCore_ORM.Models;
using Dapper;
using Microsoft.AspNetCore.Mvc;

namespace _15Net8AspNetCore_ORM.OrderRespository
{
    public class OrderDapperRespository : IOrderRespository
    {
        public DapperDBContext _DapperContext { get; set; }
        public OrderDapperRespository(DapperDBContext dapperDB)
        {
            _DapperContext = dapperDB;
        }
        public Order AddOrder(Order order)
        {
            // 1、创建链接
            using (var connect = _DapperContext.DbConnection())
            {
                int id = connect.ExecuteScalar<int>("insert into `Order` (name, price, price2) values (@name, @Price, @Price2) ; select LAST_INSERT_ID(); ", order);  // 获取插入的个数
                order.Id = id;
                return order;
            }
        }

        public void DeleteOrder(int id)
        {
            // 1、创建链接
            using (var connect = _DapperContext.DbConnection())
            {
                connect.Execute("delete from `Order` where id = @Id ", new { Id = id });
            }
        }

        public List<Order> GetAllOrder()
        {
            // 1、创建链接
            using (var connect = _DapperContext.DbConnection())
            {
                List<Order> orders = connect.Query<Order>("Select * from `Order`").ToList();

                return orders;
            }
        }

        public Order GetOrder(int id)
        {
            // 1、创建链接
            using (var connect = _DapperContext.DbConnection())
            {
                Order order = connect.QuerySingle<Order>("Select * from `Order` where id = @Id ", new { Id = id });

                return order;
            }
        }

        public void UpdateOrder(int id, Order Order)
        {
            // 1、创建链接
            using (var connect = _DapperContext.DbConnection())
            {
                connect.Execute("update `Order` set name = @name, price = @Price, price2 = @Price2 where id = @Id ", Order);
            }
        }



    }
}
